from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
from historyHandler import HistoryDialogHandler
import logging

ID, NAME = range(2)

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('AssetTabHandler')
class AssetTabHandler(object):

	def __init__(self, db, view, newButton, deleteButton, historyButton, parent=None):
		log.debug(" initializing asset table view...")
		self.db = db
		self.view = view
		self.parent = parent
		self.handleAssetView(db, newButton, deleteButton, historyButton, parent)
		
	def handleAssetView(self, db, newButton, deleteButton, historyButton, parent):
		# setting up model :
		model = QSqlTableModel(parent, db)
		model.setTable("asset")
		model.setHeaderData(ID, Qt.Horizontal, "Id")
		model.setHeaderData(NAME, Qt.Horizontal,"Name")
		model.setSort(ID, Qt.AscendingOrder)
		
		# handling the view association
		view = self.view
		view.setModel(model)
		
		# set hidden columns e.g. id ones :
		view.hideColumn(ID)
		
		# updating view :
		model.select()
		view.setSelectionMode(QTableView.SingleSelection)
		view.setSelectionBehavior(QTableView.SelectRows)
		self.resizeColumns(None)
		
		# setting up member variables :
		self.model = model
		
		# adding signals for add/delete etc...
		if parent:
			parent.connect(newButton, SIGNAL("clicked()"), self.addRecord)
			parent.connect(deleteButton, SIGNAL("clicked()"), self.deleteRecord)
			parent.connect(model, SIGNAL("beforeInsert (QSqlRecord&)"), self.resizeColumns)
			parent.connect(model, SIGNAL("beforeUpdate (int,QSqlRecord&)"), self.resizeColumns)
			# connect history dialog
			self.dlg = HistoryDialogHandler()
			parent.connect(historyButton, SIGNAL("clicked()"), self.showDialog)
			
	def showDialog(self):
		self.dlg.show(None)
		
	def addRecord(self):
		row = self.model.rowCount()
		insertedRow = self.model.insertRow(row)
		log.debug(" new row inserted : " + str(insertedRow))
		index = self.model.index(row, NAME)
		self.view.setCurrentIndex(index)
		self.view.edit(index)
	
	def resizeColumns(self, record):
		log.debug(" resize columns called on record " + str(record))
		self.view.resizeColumnsToContents()
		
	def deleteRecord(self):
		index = self.view.currentIndex()
		log.debug(" called delete record with index valid : " + str(index.isValid()))
		if not index.isValid():
			return
		record = self.model.record(index.row())
		id = record.value(ID)
		# initializing query to check if record exists :
		query = QSqlQuery()
		query.exec_("SELECT COUNT(*) FROM position WHERE asset_id = " + str(id))
		count = 0
		if query.next():
			count = query.value(0)
		if (count and QMessageBox.question(self.view, "Asset deletion", 
					"Asset is still referenced \n Remove anyway ?",
					QMessageBox.Yes|QMessageBox.No) ==
					QMessageBox.No):
			return
		self.model.removeRow(index.row())
		self.model.submitAll()